package com.marver.common.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

/**
 * DES加密
 * Created by jiangyonggang on 2017-08-07.
 */
public class DESUtils {

    public static final String DES_CRYPT_KEY = "LZFYLZFY";  //加密秘钥

    private static final String ALGORITHM = "DES";   //加密方式

    public static final String YDYX_DES_CRYPT_KEY_MIN = "YDYXYDYX";

    private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };

/*    public static String encryptDES(String encryptString, String cryptKey) throws Exception {
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(StringUtils.isNotBlank(cryptKey)?cryptKey.getBytes():DES_CRYPT_KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
        return URLEncoder.encode(new String(Base64.encode(encryptedData)),"UTF-8");

    }

    public static String decryptDES(String decryptString, String cryptKey) {
        String codeStr="";
        try {
            byte[] byteMi = Base64.decode(URLDecoder.decode(decryptString,"UTF-8"));
            IvParameterSpec zeroIv = new IvParameterSpec(iv);
            SecretKeySpec key = new SecretKeySpec(StringUtils.isNotBlank(cryptKey)?cryptKey.getBytes():DES_CRYPT_KEY.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
            byte decryptedData[] = cipher.doFinal(byteMi);
            codeStr = new String(decryptedData).trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return codeStr;
    }*/

    public static String decryptDES(String decryptString, String cryptKey){
        String codeStr="";
        try {
            if(StringUtils.isBlank(cryptKey)){
                cryptKey = DES_CRYPT_KEY;
            }
            String urlDecryptString = URLDecoder.decode(decryptString, "UTF-8");
            byte[] bytStr = org.apache.tomcat.util.codec.binary.Base64.decodeBase64(urlDecryptString.getBytes());
            DESKeySpec dks = new DESKeySpec(cryptKey.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            //key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(cryptKey.getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.DECRYPT_MODE, secretKey,paramSpec);
            byte[] bytes = cipher.doFinal(bytStr);
            codeStr = new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return codeStr;
    }

    public static String encryptDES(String encryptString, String cryptKey) throws Exception
    {
        try
        {
            if(StringUtils.isBlank(cryptKey)){
                cryptKey = DES_CRYPT_KEY;
            }

            DESKeySpec dks = new DESKeySpec(cryptKey.getBytes());

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            //key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(cryptKey.getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey,paramSpec);

            byte[] bytes = cipher.doFinal(encryptString.getBytes());
            return URLEncoder.encode(new String(org.apache.tomcat.util.codec.binary.Base64.encodeBase64(bytes)),"UTF-8");
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException {
        byte[] key = new byte[8];    //声明一个24位的字节数组，默认里面都是0
        byte[] temp = keyStr.getBytes("UTF-8");    //将字符串转成字节数组
       /*
       * 执行数组拷贝
         * System.arraycopy(源数组，从源数组哪里开始拷贝，目标数组，拷贝多少位)
         */
        if(key.length > temp.length){
            //如果temp不够24位，则拷贝temp数组整个长度的内容到key数组中
            System.arraycopy(temp, 0, key, 0, temp.length);
        }else{
            //如果temp大于24位，则拷贝temp数组24个长度的内容到key数组中
            System.arraycopy(temp, 0, key, 0, key.length);
        }
        return key;
    }
    /**
     * 用于一点游戏的解密
     * @param decryptString
     * @return
     * @throws Exception
     * @author mcx 2017-05-31
     */
    public static String ydyxDecryptDES(String decryptString,String akey) throws Exception{

        String codeStr="";
        try {
            String newStr = URLDecoder.decode(decryptString,"utf-8") ;
            byte[] byteMi = org.apache.tomcat.util.codec.binary.Base64.decodeBase64(newStr);
            IvParameterSpec zeroIv = new IvParameterSpec(iv);
            SecretKeySpec key = new SecretKeySpec(build3DesKey(akey), ALGORITHM);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
            byte decryptedData[] = cipher.doFinal(byteMi);
            codeStr = new String(decryptedData).trim();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return codeStr;
    }

    /**
     * DES算法，加密
     * 用于一点游戏的加密
     * data 待解密字符串
     * key 解密私钥，长度不能够小于8位
     * @return 解密后的字节数组
     * @throws Exception 异常
     * @author mcx 2017-05-31
     */
    public static String ydyxEncryptDES(String decryptString,String akey) throws Exception{
        try{
            IvParameterSpec zeroIv = new IvParameterSpec(iv);
            SecretKeySpec key = new SecretKeySpec(build3DesKey(akey), ALGORITHM);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            byte[] encryptedData = cipher.doFinal(decryptString.getBytes());
            //return Base64.encode(encryptedData);
            return URLEncoder.encode(new String(org.apache.tomcat.util.codec.binary.Base64.encodeBase64(encryptedData)),"UTF-8");
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

//    public static void main(String[] args) throws Exception {
//        System.out.println(encryptDES("123456",null));
//        System.out.println(decryptDES("PBEA%2FN76vDg%3D","LZFYLZFY"));
//    }
}
